<script setup lang="ts">
import { useShowPrescription } from '@/composable'
import type { IllnessTime } from '@/enums'
import { MsgType, PrescriptionStatus } from '@/enums'
import {
  getConsultFlagOptionLabel,
  getIllnessTimeOptionLabel
} from '@/services/constants'
import { useUserStore } from '@/stores'
import type { Image } from '@/types/consult'
import type { Message, Prescription } from '@/types/room'
import dayjs from 'dayjs'
import { showImagePreview, showToast } from 'vant'
import EvaluateCard from './EvaluateCard.vue'
import { useRouter } from 'vue-router'

defineProps<{
  list: Message[]
}>()

/** 预览图片 */
const previewPictures = (pictures: Image[]) => {
  if (pictures.length > 0) {
    showImagePreview(pictures.map((v) => v.url))
  } else {
    showToast('暂无图片')
  }
}

const userStore = useUserStore()

const onImageLoad = (message: Message) => {
  console.log('[ message.__noReachBottom ] >', message.__noReachBottom)
  if (message.__noReachBottom) return
  // 只有接收消息时，才需要滚到底部，如果是加载的消息列表，不需要滚到底部
  window.scrollTo(0, document.body.scrollHeight)
}

// const showPrescription = (id: string) => {
//   getPrescriptionPic(id).then((res) => {
//     showImagePreview([res])
//   })
// }

const { onShowPrescription: showPrescription } = useShowPrescription()

const router = useRouter()
const buy = (pre?: Prescription) => {
  if (pre) {
    if (pre.status === PrescriptionStatus.Invalid)
      return showToast('处方已失效')
    if (pre.status === PrescriptionStatus.NotPayment && !pre.orderId)
      return router.push({ name: 'OrderPay', query: { id: pre.id } })
    router.push(`/order/${pre.orderId}`)
  }
}
</script>

<template>
  <template v-for="v of list" :key="v.id">
    <!-- 患者卡片 MsgType = 21 -->
    <div v-if="v.msgType === MsgType.CardPat" class="msg msg-illness">
      <div class="patient van-hairline--bottom">
        <p>
          {{ v.msg.consultRecord?.patientInfo.name }}
          {{ v.msg.consultRecord?.patientInfo.genderValue }}
          {{ v.msg.consultRecord?.patientInfo.age }}岁
        </p>
        <p>
          {{
            getIllnessTimeOptionLabel(
              v.msg.consultRecord?.illnessTime as IllnessTime
            )
          }}
          |
          {{
            getConsultFlagOptionLabel(v.msg.consultRecord?.consultFlag as 0 | 1)
          }}
        </p>
      </div>
      <van-row>
        <van-col span="6">病情描述</van-col>
        <van-col span="18">{{ v.msg.consultRecord?.illnessDesc }}</van-col>
        <van-col span="6">图片</van-col>
        <van-col
          span="18"
          @click="previewPictures(v.msg.consultRecord?.pictures as Image[])"
          >点击查看</van-col
        >
      </van-row>
    </div>
    <!-- 通知-通用 MsgType = 31 -->
    <div v-else-if="v.msgType === MsgType.Notify" class="msg msg-tip">
      <div class="content">
        <span>{{ v.msg.content }}</span>
      </div>
    </div>
    <!-- 通知-温馨提示 MsgType = 32 -->
    <div v-else-if="v.msgType === MsgType.NotifyTip" class="msg msg-tip">
      <div class="content">
        <span class="green">温馨提示：</span>
        <span>{{ v.msg.content }}</span>
      </div>
    </div>
    <!-- 发送文字 MsgType = 1 && v.from === 当前登录用户的id -->
    <div
      v-else-if="v.msgType === MsgType.MsgText && v.from === userStore.user?.id"
      class="msg msg-to"
    >
      <div class="content">
        <div class="time">{{ dayjs(v.createTime).format('HH:mm') }}</div>
        <div class="pao">{{ v.msg.content }}</div>
      </div>
      <van-image :src="v.fromAvatar" />
    </div>
    <!-- 接收文字 MsgType = 1 && v.from !== 当前登录用户的id -->
    <div
      v-else-if="v.msgType === MsgType.MsgText && v.from !== userStore.user?.id"
      class="msg msg-from"
    >
      <van-image :src="v.fromAvatar" />
      <div class="content">
        <div class="time">{{ dayjs(v.createTime).format('HH:mm') }}</div>
        <div class="pao">{{ v.msg.content }}</div>
      </div>
    </div>

    <!-- 发送图片 MsgType = 4 && v.from === 当前登录用户的id -->
    <div
      v-else-if="
        v.msgType === MsgType.MsgImage && v.from === userStore.user?.id
      "
      class="msg msg-to"
    >
      <div class="content">
        <div class="time">{{ dayjs(v.createTime).format('HH:mm') }}</div>
        <van-image
          fit="contain"
          :src="v.msg.picture?.url"
          @load="onImageLoad(v)"
        />
      </div>
      <van-image :src="v.fromAvatar" />
    </div>

    <!-- 接收图片 MsgType = 4 && v.from !== 当前登录用户的id -->
    <div
      v-else-if="
        v.msgType === MsgType.MsgImage && v.from !== userStore.user?.id
      "
      class="msg msg-from"
    >
      <van-image :src="v.fromAvatar" />
      <div class="content">
        <div class="time">20:12</div>
        <!-- 
          图片加载也是需要时间的，当图片没有加载完成之前，高度是没有撑开的，
          所以需要在图片加载完之后，再让滚动条触底
         -->
        <van-image
          fit="contain"
          :src="v.msg.picture?.url"
          @load="onImageLoad(v)"
        />
      </div>
    </div>

    <!-- 处方 -->
    <div class="msg msg-recipe" v-if="v.msgType === MsgType.CardPre">
      <div class="content" v-if="v.msg.prescription">
        <div class="head van-hairline--bottom">
          <div class="head-tit">
            <h3>电子处方</h3>
            <p @click="showPrescription(v.msg.prescription.id)">
              原始处方 <van-icon name="arrow"></van-icon>
            </p>
          </div>
          <p>
            {{ v.msg.prescription.name }}
            {{ v.msg.prescription.genderValue }}
            {{ v.msg.prescription.age }}岁
            {{ v.msg.prescription.diagnosis }}
          </p>
          <p>开方时间：{{ v.msg.prescription.createTime }}</p>
        </div>
        <div class="body">
          <div
            class="body-item"
            v-for="med in v.msg.prescription.medicines"
            :key="med.id"
          >
            <div class="durg">
              <p>{{ med.name }} {{ med.specs }}</p>
              <p>{{ med.usageDosag }}</p>
            </div>
            <div class="num">x{{ med.quantity }}</div>
          </div>
        </div>
        <div class="foot">
          <span @click="buy(v.msg.prescription)">购买药品</span>
        </div>
      </div>
    </div>

    <!-- 通知-结束 MsgType = 33 -->
    <div
      v-else-if="v.msgType === MsgType.NotifyCancel"
      class="msg msg-tip msg-tip-cancel"
    >
      <div class="content">
        <span>{{ v.msg.content }}</span>
      </div>
    </div>

    <!-- 待评价、已评价 MsgType = 23 || 24 -->
    <div
      class="msg msg-comment"
      v-if="v.msgType === MsgType.CardEvaForm || v.msgType === MsgType.CardEva"
    >
      <evaluate-card :evaluateDoc="v.msg.evaluateDoc" />
    </div>
  </template>
</template>

<style lang="scss" scoped>
@import '@/styles/room.scss';
</style>
